<template>
  <div class="my-collections">
    <!-- 头部区域 -->
    <div class="collections-header">
      <h2>我的合集</h2>
      <div class="collections-actions">
        <el-button type="primary" @click="showCreateDialog" round>
          <i class="el-icon-plus"></i>
          创建合集
        </el-button>
        <el-dropdown trigger="click" @command="handleFilterCommand">
          <span class="filter-dropdown">
            <span>{{ currentFilter.label }}</span>
            <i class="el-icon-arrow-down"></i>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="filter in filters"
                :key="filter.value"
                :command="filter.value"
              >
                {{ filter.label }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="collections-loading">
      <div class="anime-loading">
        <div class="anime-loading-item"></div>
        <div class="anime-loading-item"></div>
        <div class="anime-loading-item"></div>
      </div>
      <p>加载合集中...</p>
    </div>

    <!-- 空状态 -->
    <div v-else-if="collections.length === 0" class="collections-empty">
      <img
        src="/src/assets/anime/images/banner14.png"
        alt="空状态图片"
        class="empty-image"
      />
      <p>你还没有创建任何合集哦~</p>
      <el-button type="primary" @click="showCreateDialog" round>
        创建第一个合集
      </el-button>
    </div>

    <!-- 合集列表 -->
    <div v-else class="collections-grid">
      <div
        v-for="collection in collections"
        :key="collection.id"
        class="collection-card"
        @click="viewCollection(collection.id)"
      >
        <div class="collection-cover">
          <img :src="getCollectionCover(collection)" alt="合集封面" />
          <div class="collection-info">
            <span class="video-count">{{ collection.videoCount }}个视频</span>
            <span class="play-count">
              <i class="el-icon-view"></i>
              {{ formatCount(collection.playCount) }}
            </span>
          </div>
          <div class="hover-actions">
            <el-button
              type="primary"
              icon="el-icon-video-play"
              circle
              @click.stop="playCollection(collection.id)"
            ></el-button>
            <el-dropdown
              trigger="click"
              @command="(cmd) => handleCollectionCommand(cmd, collection.id)"
              @click.stop
            >
              <el-button type="info" icon="el-icon-more" circle></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit">编辑合集</el-dropdown-item>
                  <el-dropdown-item command="delete">删除合集</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <div class="collection-title">{{ collection.title }}</div>
        <div class="collection-date">{{ collection.updateDate }} 更新</div>
      </div>
    </div>

    <!-- 创建/编辑合集对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑合集' : '创建合集'"
      width="30%"
      custom-class="collection-dialog"
    >
      <el-form
        :model="collectionForm"
        :rules="rules"
        ref="collectionFormRef"
        label-width="80px"
      >
        <el-form-item label="名称" prop="title">
          <el-input
            v-model="collectionForm.title"
            placeholder="请输入合集名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="collectionForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入合集描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <div class="cover-uploader">
            <img
              v-if="collectionForm.coverUrl"
              :src="collectionForm.coverUrl"
              class="cover-image"
            />
            <i v-else class="el-icon-plus"></i>
            <span class="upload-text">点击上传封面</span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCollectionForm">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
      custom-class="delete-dialog"
    >
      <div class="delete-content">
        <p>确定要删除该合集吗？合集中的视频不会被删除。</p>
        <p class="warning">此操作不可恢复！</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElForm } from 'element-plus'

// 路由
const router = useRouter()

// 状态管理
const loading = ref(true)
const collections = ref([])
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const isEdit = ref(false)
const currentCollectionId = ref<number | null>(null)
const collectionFormRef = ref<InstanceType<typeof ElForm> | null>(null)

// 表单数据
const collectionForm = reactive({
  title: '',
  description: '',
  coverUrl: '',
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入合集名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' },
  ],
}

// 筛选选项
const filters = [
  { label: '最近更新', value: 'recent' },
  { label: '最多播放', value: 'popular' },
  { label: '创建时间', value: 'created' },
]
const currentFilter = ref(filters[0])

// 处理筛选命令
const handleFilterCommand = (command) => {
  const selected = filters.find((filter) => filter.value === command)
  if (selected) {
    currentFilter.value = selected
    fetchCollections()
  }
}

// 格式化数字
const formatCount = (count) => {
  if (!count && count !== 0) return '0'
  if (count < 10000) {
    return count.toString()
  } else if (count < 100000000) {
    return (count / 10000).toFixed(1) + '万'
  } else {
    return (count / 100000000).toFixed(1) + '亿'
  }
}

// 获取合集封面
const getCollectionCover = (collection) => {
  if (collection.coverUrl) {
    return collection.coverUrl
  }
  // 默认返回随机banner图
  const randomBanner = Math.floor(Math.random() * 14) + 1
  return `/src/assets/anime/images/banner${randomBanner}.png`
}

// 查看合集详情
const viewCollection = (id) => {
  router.push(`/collection/${id}`)
}

// 播放合集
const playCollection = (id) => {
  // 假设是播放合集中的第一个视频
  ElMessage.success('开始播放合集')
  router.push(`/collection/${id}`)
}

// 处理合集操作命令
const handleCollectionCommand = (command, id) => {
  if (command === 'edit') {
    editCollection(id)
  } else if (command === 'delete') {
    showDeleteDialog(id)
  }
}

// 显示创建合集对话框
const showCreateDialog = () => {
  isEdit.value = false
  collectionForm.title = ''
  collectionForm.description = ''
  collectionForm.coverUrl = ''
  dialogVisible.value = true
}

// 编辑合集
const editCollection = (id) => {
  isEdit.value = true
  currentCollectionId.value = id

  // 获取当前合集信息填充表单
  const collection = collections.value.find((c) => c.id === id)
  if (collection) {
    collectionForm.title = collection.title
    collectionForm.description = collection.description
    collectionForm.coverUrl =
      collection.coverUrl || getCollectionCover(collection)
  }

  dialogVisible.value = true
}

// 显示删除确认对话框
const showDeleteDialog = (id) => {
  currentCollectionId.value = id
  deleteDialogVisible.value = true
}

// 确认删除合集
const confirmDelete = async () => {
  try {
    // 模拟删除操作
    await new Promise((resolve) => setTimeout(resolve, 800))

    // 从列表中移除
    collections.value = collections.value.filter(
      (c) => c.id !== currentCollectionId.value,
    )

    ElMessage.success('删除成功')
    deleteDialogVisible.value = false
    currentCollectionId.value = null
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 提交合集表单
const submitCollectionForm = async () => {
  if (!collectionFormRef.value) return

  try {
    await collectionFormRef.value.validate()

    // 模拟提交操作
    await new Promise((resolve) => setTimeout(resolve, 800))

    if (isEdit.value && currentCollectionId.value) {
      // 更新已有合集
      const index = collections.value.findIndex(
        (c) => c.id === currentCollectionId.value,
      )
      if (index !== -1) {
        collections.value[index] = {
          ...collections.value[index],
          title: collectionForm.title,
          description: collectionForm.description,
          coverUrl: collectionForm.coverUrl,
          updateDate: new Date().toLocaleDateString(),
        }
      }
      ElMessage.success('更新成功')
    } else {
      // 创建新合集
      const newCollection = {
        id: Date.now(),
        title: collectionForm.title,
        description: collectionForm.description,
        coverUrl: collectionForm.coverUrl,
        videoCount: 0,
        playCount: 0,
        createDate: new Date().toLocaleDateString(),
        updateDate: new Date().toLocaleDateString(),
      }
      collections.value.unshift(newCollection)
      ElMessage.success('创建成功')
    }

    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 获取合集列表
const fetchCollections = async () => {
  loading.value = true
  try {
    // 模拟API请求延迟
    await new Promise((resolve) => setTimeout(resolve, 1000))

    // 模拟合集数据
    const mockCollections = [
      {
        id: 1,
        title: '足球热点赛事集锦',
        description:
          '收录了各种精彩的足球赛事和热点事件，内容包括欧洲五大联赛、欧冠、世界杯等比赛的精彩瞬间。',
        coverUrl: '/src/assets/anime/images/banner10.png',
        videoCount: 12,
        playCount: 45800,
        createDate: '2022-01-10',
        updateDate: '2022-08-20',
      },
      {
        id: 2,
        title: '动漫角色配音教程',
        description:
          '专业的声优教你如何为动漫角色配音，包含发声技巧、情感表达、配音实践等内容。',
        coverUrl: '/src/assets/anime/images/banner2.png',
        videoCount: 8,
        playCount: 32400,
        createDate: '2022-02-05',
        updateDate: '2022-07-15',
      },
      {
        id: 3,
        title: '国漫精选',
        description:
          '精选国产优质动画片段，包括《大圣归来》、《哪吒之魔童降世》等经典作品的创作幕后。',
        coverUrl: '/src/assets/anime/images/banner5.png',
        videoCount: 15,
        playCount: 67900,
        createDate: '2022-03-12',
        updateDate: '2022-08-10',
      },
      {
        id: 4,
        title: '日式料理制作教程',
        description:
          '从寿司到拉面，从天妇罗到居酒屋小食，详细讲解日本料理的制作方法和技巧。',
        coverUrl: '/src/assets/anime/images/banner7.png',
        videoCount: 20,
        playCount: 89200,
        createDate: '2022-01-20',
        updateDate: '2022-08-05',
      },
      {
        id: 5,
        title: '电竞赛事解说精选',
        description:
          '收录各大电竞赛事的精彩解说片段，包括LOL、DOTA2、王者荣耀等游戏的职业比赛。',
        coverUrl: '/src/assets/anime/images/banner3.png',
        videoCount: 18,
        playCount: 124500,
        createDate: '2022-04-15',
        updateDate: '2022-08-01',
      },
      {
        id: 6,
        title: '我的世界红石教程',
        description:
          '从基础到进阶的我的世界红石机关教程，教你制作各种实用的自动化装置。',
        coverUrl: '/src/assets/anime/images/banner8.png',
        videoCount: 14,
        playCount: 76300,
        createDate: '2022-05-01',
        updateDate: '2022-07-25',
      },
    ]

    // 根据筛选条件排序
    if (currentFilter.value.value === 'popular') {
      mockCollections.sort((a, b) => b.playCount - a.playCount)
    } else if (currentFilter.value.value === 'created') {
      mockCollections.sort(
        (a, b) =>
          new Date(b.createDate).getTime() - new Date(a.createDate).getTime(),
      )
    } else {
      // 默认按最近更新排序
      mockCollections.sort(
        (a, b) =>
          new Date(b.updateDate).getTime() - new Date(a.updateDate).getTime(),
      )
    }

    collections.value = mockCollections
  } catch (error) {
    console.error('获取合集列表失败:', error)
    ElMessage.error('获取合集列表失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCollections()
})
</script>

<style scoped lang="scss">
:root {
  --kawaii-pink: #ff9ed2;
  --kawaii-blue: #78c4ff;
  --kawaii-purple: #c78bff;
  --kawaii-yellow: #ffe67b;
  --kawaii-green: #a2e8af;
  --soft-shadow: 0 3px 15px rgba(0, 0, 0, 0.1);
}

.my-collections {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;

  .collections-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;

    h2 {
      font-size: 24px;
      color: #333;
      font-weight: 600;
      margin: 0;

      &::after {
        content: '';
        display: block;
        width: 40px;
        height: 3px;
        background: linear-gradient(90deg, var(--kawaii-pink), var(--kawaii-purple));
        margin-top: 5px;
        border-radius: 3px;
      }
    }

    .collections-actions {
      display: flex;
      align-items: center;

      .filter-dropdown {
        display: flex;
        align-items: center;
        padding: 8px 15px;
        border-radius: 20px;
        background-color: #f5f7fa;
        margin-left: 15px;
        cursor: pointer;
        color: #606266;
        font-size: 14px;

        &:hover {
          background-color: #ebeef5;
        }

        i {
          margin-left: 5px;
        }
      }

      .el-button {
        background: linear-gradient(45deg, var(--kawaii-blue), var(--kawaii-purple));
        border: none;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(123, 104, 238, 0.3);
        }
      }
    }
  }

  .collections-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300px;

    .anime-loading {
      display: flex;
      justify-content: center;
      margin-bottom: 20px;

      .anime-loading-item {
        width: 15px;
        height: 15px;
        margin: 0 5px;
        border-radius: 50%;
        background-color: var(--kawaii-purple);
        animation: bounce 1.5s infinite ease-in-out both;

        &:nth-child(1) {
          animation-delay: -0.3s;
          background-color: var(--kawaii-pink);
        }

        &:nth-child(2) {
          animation-delay: -0.15s;
          background-color: var(--kawaii-blue);
        }
      }
    }

    p {
      color: #909399;
      font-size: 16px;
    }
  }

  .collections-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 400px;

    .empty-image {
      width: 200px;
      height: 200px;
      object-fit: cover;
      border-radius: 50%;
      margin-bottom: 20px;
      opacity: 0.8;
      box-shadow: var(--soft-shadow);
    }

    p {
      color: #909399;
      font-size: 16px;
      margin-bottom: 20px;
    }

    .el-button {
      background: linear-gradient(45deg, var(--kawaii-blue), var(--kawaii-purple));
      border: none;
      padding: 10px 25px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(123, 104, 238, 0.3);
      }
    }
  }

  .collections-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 25px;

    .collection-card {
      background-color: #fff;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: var(--soft-shadow);
      transition: all 0.3s ease;
      cursor: pointer;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);

        .hover-actions {
          opacity: 1;
        }
      }

      .collection-cover {
        position: relative;
        height: 160px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.5s ease;
        }

        .collection-info {
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          padding: 10px;
          background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
          color: #fff;
          font-size: 12px;
          display: flex;
          justify-content: space-between;

          .video-count {
            background-color: rgba(0, 0, 0, 0.5);
            padding: 2px 8px;
            border-radius: 10px;
          }

          .play-count {
            display: flex;
            align-items: center;

            i {
              margin-right: 4px;
            }
          }
        }

        .hover-actions {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.4);
          display: flex;
          justify-content: center;
          align-items: center;
          gap: 15px;
          opacity: 0;
          transition: opacity 0.3s ease;

          .el-button {
            &:first-child {
              background: linear-gradient(45deg, var(--kawaii-pink), var(--kawaii-purple));
              border: none;
              transform: scale(1.1);
            }

            &:last-child {
              background: rgba(255, 255, 255, 0.8);
              color: #303133;
              border: none;
            }

            &:hover {
              transform: scale(1.15);
            }
          }
        }
      }

      .collection-title {
        padding: 12px 15px 5px;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .collection-date {

        .cover-image {
          position: absolute;
          width: 85%;
          height: 85%;
          object-fit: cover;
          border-radius: 4px;
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
          transition: all 0.3s ease;
        }
      }

      .collection-stats {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
        color: #fff;
        padding: 10px;
        display: flex;
        justify-content: space-between;
        font-size: 12px;

        i {
          margin-right: 4px;
        }
      }
    }

    .collection-info {
      padding: 15px;

      .collection-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        margin: 0 0 8px;
        transition: color 0.3s;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .collection-desc {
        color: #606266;
        font-size: 14px;
        margin: 0 0 15px;
        height: 40px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .collection-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .update-time {
          color: #909399;
          font-size: 12px;
        }

        .collection-actions {
          display: flex;

          i {
            margin-left: 10px;
            font-size: 16px;
            color: #909399;
            cursor: pointer;

            &:hover {
              color: #409eff;
            }

            &.el-icon-delete:hover {
              color: #f56c6c;
            }
          }
        }
      }
    }
  }
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.upload-covers {
  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
}

@keyframes bounce {

  0%,
  80%,
  100% {
    transform: scale(0);
  }

  40% {
    transform: scale(1);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
